
package com.crowdfunding.circle.common.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.crowdfunding.circle.common.param.SessionUserInfo;

/**
 * 登录过滤器
 *
 * @author 朱国军
 * @since 1.0
 * @version 2016年1月9日 朱国军
 */
public class LoginFilter implements Filter {

    /** 不需要登录验证的URL */
    private String[] excludeUrl;

    private Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludeUrls = filterConfig.getInitParameter("ExcludeUrl");
        if (StringUtils.isNotBlank(excludeUrls)) {
            this.excludeUrl = StringUtils.split(excludeUrls, ",");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {
            Object userInfo = httpRequest.getSession().getAttribute("sessionUserInfo");
            // 用户未登录，需要登录
            if (userInfo == null || StringUtils.isBlank(((SessionUserInfo) userInfo).getUserId())) {
                String requestUrl = httpRequest.getRequestURI();
                Boolean needLogin = true;
                if (excludeUrl != null) {
                    for (String uri : excludeUrl) {
                        if (StringUtils.isNotBlank(uri.trim()) && requestUrl.contains(uri.trim())) {
                            needLogin = false;
                            break;
                        }
                    }
                }
                if (needLogin) {
                    httpResponse.sendRedirect(httpRequest.getContextPath() + "/uncheck/login");
                }
            }
        } catch (Exception e) {
            logger.error("登录过滤器出错！", e);
        }

        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            logger.error("登录过滤器doFilter出错！", e);
        }
    }

    @Override
    public void destroy() {

    }
}
